package org.example;

import java.util.ArrayList;
import java.util.List;

public class Main {
    private static String sourceCode;

    public static List<String> extractStrings(String sourceCode) {
        List<String> stringsList = new ArrayList<>();
        StringBuilder currentString = new StringBuilder();
        State currentState = State.START;

        for (int i = 0; i < sourceCode.length(); i++) {
            char currentChar = sourceCode.charAt(i);

            switch (currentState) {
                case START:
                    if (currentChar == '"') {
                        currentState = State.INSIDE_STRING;
                    }
                    break;
                case INSIDE_STRING:
                    if (currentChar == '"') {
                        if (i > 0 && sourceCode.charAt(i - 1)!= '\\') {
                            stringsList.add(currentString.toString());
                            currentString.setLength(0);
                            currentState = State.START;
                        } else {
                            currentString.deleteCharAt(currentString.length() - 1);
                            currentString.append('"');
                        }
                    } else if (currentChar == '\\') {
                        if (i < sourceCode.length() - 1) {
                            char nextChar = sourceCode.charAt(i + 1);
                            currentString.append(handleEscape(nextChar));
                            i++;
                        }
                    } else {
                        currentString.append(currentChar);
                    }
                    break;
            }
        }

        return stringsList;
    }

    private static char handleEscape(char nextChar) {
        if (nextChar == '"') {
            return '"';
        } else if (nextChar == '\\') {
            return '\\';
        }
        return nextChar;
    }

    private enum State {
        START,
        INSIDE_STRING
    }
    public  static  void  main(String [] args) {
        String sourceCode = "\"一般学习一门编程语言的时候，基本上第一个程序是输出\\\"Hello World!\\\"\"";
        List<String> extractedStrings = Main.extractStrings(sourceCode);
        for (String str : extractedStrings) {
            System.out.println(str);
        }
    }
}